#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <thread>
#include <mutex>
#include <QMainWindow>
#include "movingChargeTcpServer.h"
#include "servoControl.h"

#define OPT_SERVO_ERR               (4)                                         //电机操作故障
#define EMERGENCY_BUTTON_LIFT_ON    (0)                                         //紧急按钮抬起
#define EMERGENCY_BUTTON_PRESS_DOWN (1)//紧急按钮按下
static const int AXIS_X = 0;


enum TaskEnum{
    ZERO_AXIS_X = 1001,
    ZERO_AXIS_Y,
    MOVE_AXIS_X,
    MOVE_AXIS_Y,
    MOVE_HOME,
    ENABLE,
    DISENABLE,
    MOVE_AXIS_X_NUM,
    TASK_WAIT
};


namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void closeEvent(QCloseEvent * event);

    void on_pushButton_8_clicked();
    void onOpenDone(bool);
    void onMoveDone(double, bool, bool);

    void on_pushButton_3_clicked();

    void on_pushButton_clicked();

    void on_pushButton_2_clicked();

    void on_pushButton_5_clicked();

    void on_pushButton_4_clicked();

    void on_pushButton_6_clicked();

    void on_pushButton_7_clicked();

    void on_pushButton_9_clicked();

    void on_pushButton_10_clicked();

    void slot_move_servo(int num);

Q_SIGNALS:
    void openDone(bool);
    void moveDone(double x, bool result, bool popup);
    void sigReplyClient(std::string num, std::string reslut);

private:
    Ui::MainWindow *ui;
    std::unique_ptr<servoControl>   m_servo;
    MovingChargeTcpServer moving_server;
    void openDev();

    int opt_errno;
    bool servo_move_axis(int axis_num, int dist_mm,int& opt_errno);

    /*工作线程*/
    int mWorkerCurTask;
    bool mWorkerRunnig = false;
    std::condition_variable mWorkercond;
    bool mWorkerRecvStatus;
    std::mutex mWorkerProcMutex;
    std::thread worker;
    void workThreadFun();

    /*监控线程*/
    bool mMonitorRunnig= false;
    int mMonitorEmergencySwitch = EMERGENCY_BUTTON_LIFT_ON;
    std::thread monitor;
    void monitorThreadFun();
    int reconnect_servo();

    /*电机ui显示线程*/
    std::thread servoUi;
    bool mServoUiRunnig = false;
    void servoUiThreadFun();
    void servo_get_cur_posxy(double &x);
    void servo_update_ui();
    bool servo_reset_home();
    void save_point_file(std::string key);

    void loadInit();
    double pointDis[4]={};
    int cur_point_num = 0;
};

#endif // MAINWINDOW_H
